//
//  SGPageToolbar.m
//  Labanbrowser
//
//  Created by Simon Grätzer on 17.12.12.
//
//
//  Copyright (c) 2012 Simon Grätzer
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import "SGPageToolbar.h"
#import "SGPageViewController.h"
#import "SGTabDefines.h"
#import "SGSearchField.h"

#import "BookmarkPage.h"
#import "SettingsController.h"
#import "WelcomePage.h"
#import "SGNavViewController.h"
#import "StringModifier.h"
#import "SGWebViewController.h"
#import "MyUtilities.h"
#import "StaticVariables.h"
@implementation SGPageToolbar {
    UIColor *_bottomColor;
    BOOL _searchMaskVisible;
    
}
@synthesize isInFullscreenMode;
@synthesize delegate;

double const_edgeSize = 20;

- (void) relocalize{
    [_cancelButton setTitle:[MyUtilities getLocalizeStringFromTag:@"ActionCancel"] forState:UIControlStateNormal];
    [_searchField relocalize];
}

- (id)initWithFrame:(CGRect)frame browser:(SGPageViewController *)browser {
    self = [super initWithFrame:frame];
    if (self) {
        _browser = browser;
        self.delegate = browser;
        _bottomColor = kTabColor;
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        self.backgroundColor = [UIColor clearColor];
        
        CGRect btnRect = CGRectMake(0, 0, 40, 40);
        _addNewTabButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _addNewTabButton.frame = btnRect;
        _addNewTabButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
        _addNewTabButton.backgroundColor = [UIColor clearColor];
        _addNewTabButton.showsTouchWhenHighlighted = YES;
        _addNewTabButton.enabled = YES;
        [_addNewTabButton setImage:[UIImage imageNamed:@"ic_browser_toolbar_newpage_nor.png"] forState:UIControlStateNormal];
        [_addNewTabButton addTarget:self.browser action:@selector(addTab) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_addNewTabButton];
        
        /*
         _forwardButton = [UIButton buttonWithType:UIButtonTypeCustom];
         _forwardButton.frame = btnRect;
         _forwardButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
         _forwardButton.backgroundColor = [UIColor clearColor];
         _forwardButton.showsTouchWhenHighlighted = YES;
         [_forwardButton setImage:[UIImage imageNamed:@"right"] forState:UIControlStateNormal];
         [_forwardButton addTarget:self.browser action:@selector(goForward) forControlEvents:UIControlEventTouchUpInside];
         _forwardButton.enabled = self.browser.canGoForward;
         [self addSubview:_forwardButton];
         */
        
        /*
         btnRect = CGRectMake(0, (frame.size.height - 36)/2, 36, 36);
         btnRect.origin.x = frame.size.width - 80;
         _optionsButton = [UIButton buttonWithType:UIButtonTypeCustom];
         _optionsButton.frame = btnRect;
         _optionsButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
         _optionsButton.backgroundColor = [UIColor clearColor];
         [_optionsButton setImage:[UIImage imageNamed:@"grip"] forState:UIControlStateNormal];
         [_optionsButton setImage:[UIImage imageNamed:@"grip-pressed"] forState:UIControlStateHighlighted];
         [_optionsButton addTarget:self action:@selector(showOptions:) forControlEvents:UIControlEventTouchUpInside];
         [self addSubview:_optionsButton];
         
         btnRect.origin.x = frame.size.width - 40;
         _tabsButton = [UIButton buttonWithType:UIButtonTypeCustom];
         _tabsButton.frame = btnRect;
         _tabsButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
         _tabsButton.backgroundColor = [UIColor clearColor];
         _tabsButton.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 0, 0);
         _tabsButton.titleLabel.font = [UIFont systemFontOfSize:12.5];
         [_tabsButton setBackgroundImage:[UIImage imageNamed:@"expose"] forState:UIControlStateNormal];
         [_tabsButton setBackgroundImage:[UIImage imageNamed:@"expose-pressed"] forState:UIControlStateHighlighted];
         [_tabsButton setTitle:@"0" forState:UIControlStateNormal];
         [_tabsButton setTitleColor:UIColorFromHEX(0x2E2E2E) forState:UIControlStateNormal];
         [_tabsButton addTarget:self action:@selector(pressedTabsButton:) forControlEvents:UIControlEventTouchUpInside];
         [self addSubview:_tabsButton];
         */
        
        btnRect = CGRectMake(0, (frame.size.height - const_edgeSize)/2, const_edgeSize, const_edgeSize);
        btnRect.origin.x = frame.size.width - const_edgeSize - 2;
        _cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _cancelButton.frame = btnRect;
        _cancelButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
        _cancelButton.backgroundColor = [UIColor clearColor];
        [_cancelButton setImage:[UIImage imageNamed:@"close_search.png"] forState:UIControlStateNormal];
        //_cancelButton.titleLabel.font = [UIFont fontWithName:@"HelveticaNeue" size:15];
        //[_cancelButton setTitle:[MyUtilities getLocalizeStringFromTag:@"ActionCancel"] forState:UIControlStateNormal];
        //[_cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_cancelButton addTarget:self action:@selector(cancelSearchButton:) forControlEvents:UIControlEventTouchUpInside];
        _cancelButton.hidden = YES;
        [self addSubview:_cancelButton];
        
        _searchField = [[SGSearchField alloc] initWithDelegate:self];
        [self.searchField.stopItem addTarget:self.browser action:@selector(stop) forControlEvents:UIControlEventTouchUpInside];
        [self.searchField.reloadItem addTarget:self.browser action:@selector(reload) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_searchField];
        
        [self.searchField.favouriteItem addTarget:self action:@selector(addToFavouriteAction) forControlEvents:UIControlEventTouchUpInside];
        
        _searchController = [SGSearchViewController new];
        _searchController.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        
        _searchController.delegate = self;
        _currentHoldingBookmark = nil;
    }
    return self;
}

- (void)layoutSubviews {
    const CGFloat margin = 2;
    CGFloat width = self.bounds.size.width;
    CGFloat height = self.bounds.size.height;
    
    CGFloat posX = margin;
    CGFloat searchWidth;
    
    searchWidth = width - posX  -const_edgeSize- 3*margin;
    
    if (!_searchMaskVisible) {
        _addNewTabButton.frame = CGRectMake(posX, (height - _addNewTabButton.frame.size.height)/2,
                                            _addNewTabButton.frame.size.width, _addNewTabButton.frame.size.height);
        
        posX += _addNewTabButton.frame.size.width + margin;
        /*
         _forwardButton.frame = CGRectMake(posX, (height - _forwardButton.frame.size.height)/2,
         _forwardButton.frame.size.width, _forwardButton.frame.size.height);
         
         if (_forwardButton.enabled)
         posX += _forwardButton.frame.size.width + margin;
         */
        
        searchWidth = width - posX - 3*margin;
    }
    
    
    _searchField.frame = CGRectMake(posX, (height - _searchField.frame.size.height)/2,
                                    searchWidth, _searchField.frame.size.height);
}

- (void)drawRect:(CGRect)rect {
    /*
     CGContextRef context = UIGraphicsGetCurrentContext();
     CGPoint topCenter = CGPointMake(CGRectGetMidX(self.bounds), 0.0f);
     CGPoint bottomCenter = CGPointMake(CGRectGetMidX(self.bounds), self.bounds.size.height);
     CGFloat locations[2] = {0.00, 1.0};
     
     CGFloat redEnd, greenEnd, blueEnd, alphaEnd;
     [_bottomColor getRed:&redEnd green:&greenEnd blue:&blueEnd alpha:&alphaEnd];
     //Two colour components, the start and end colour both set to opaque. Red Green Blue Alpha
     CGFloat components[8] = { 244./255., 245./255., 247./255., 1.0, redEnd, greenEnd, blueEnd, 1.0};
     CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
     
     CGGradientRef gradient = CGGradientCreateWithColorComponents(colorspace, components, locations, 2);
     CGContextDrawLinearGradient(context, gradient, topCenter, bottomCenter, 0);
     CGGradientRelease(gradient);
     CGColorSpaceRelease(colorspace);
     */
}

- (void)addToFavouriteAction{
    NSLog(@"favourite!!");
    //[self.browser.view addSubview:[[StaticVariables shareVariables]editorView]];
    [self.browser.view bringSubviewToFront:[[StaticVariables shareVariables]editorView]];
    [[[StaticVariables shareVariables]editorView]show];
    
    if(self.currentHoldingBookmark!=nil){
        [[[StaticVariables shareVariables] editorView] receiveModel:self.currentHoldingBookmark WithType:UpdateBookmark];
    }else{
        HistoryModel* matchHistory=(HistoryModel*)[[[StaticVariables shareVariables]historyAccess]findByURL:[self.browser URL].absoluteString];
        [[[StaticVariables shareVariables] editorView] receiveModel:matchHistory WithType:AddBookmark];
    }
}

-(void)updateStar{
    BookmarkModel* bookmarkOnDB=[[[StaticVariables shareVariables]bookmarkAccess]findByURL:[self.browser URL].absoluteString];
    [self.searchField changeImageBasedOnFoundBookmark:bookmarkOnDB];
    self.currentHoldingBookmark = bookmarkOnDB;
}

- (void)updateChrome {
    if (!([self.searchField isFirstResponder] || _searchMaskVisible))
        self.searchField.text = [self.browser URL].absoluteString;
    
    // NSString *text = [NSString stringWithFormat:@"%d", self.browser.count];
    // [_tabsButton setTitle:text forState:UIControlStateNormal];
    
    
    
    if (self.browser.canStopOrReload) {
        if ([self.browser isLoading]) {
            self.searchField.state = SGSearchFieldStateStop;
            //self.progressView.hidden = NO;
            
            BookmarkModel* bookmarkOnDB=[[[StaticVariables shareVariables]bookmarkAccess]findByURL:[self.browser URL].absoluteString];
            self.currentHoldingBookmark = bookmarkOnDB;
            [self.searchField changeImageBasedOnFoundBookmark:self.currentHoldingBookmark];
            
        } else {
            self.searchField.state = SGSearchFieldStateReload;
            
            //sync with addressbar
            if([self.browser.selectedViewController isKindOfClass:[SGWebViewController class]]){
                SGWebViewController* webVC = (SGWebViewController*)self.browser.selectedViewController;
                //[webVC.progressBar setProgress:1 animated:YES];
            }
            //self.progressView.hidden = YES;
        }
    } else {
        self.searchField.state = SGSearchFieldStateDisabled;
        //self.progressView.hidden = YES;
    }
//important_Xh
//    if([self.browser.selectedViewController isKindOfClass:[HomePageViewController class]]){
//        self.searchField.favouriteItem.enabled = NO;
//    }else{
//        self.searchField.favouriteItem.enabled = YES;
//    }
    
    
    
}

#pragma mark - IBAction

- (IBAction)cancelSearchButton:(id)sender {
    [self dismissSearchController];
    [self.searchField resignFirstResponder];
    [self endEdit];
}

- (IBAction)pressedTabsButton:(id)sender {
    [self.browser setExposeMode:YES animated:YES];
}

- (IBAction)showOptions:(UIButton *)sender {
    /*
     if (!NSClassFromString(@"SLComposeViewController")) {// iOS <= 5.1
     self.actionSheet = [[UIActionSheet alloc] initWithTitle:nil
     delegate:self
     cancelButtonTitle:NSLocalizedString(@"Cancel", nil)
     destructiveButtonTitle:nil
     otherButtonTitles:
     NSLocalizedString(@"Bookmarks", @"Bookmarks"),
     NSLocalizedString(@"Tweet", @"Tweet the current url"),
     NSLocalizedString(@"Email URL", nil),
     NSLocalizedString(@"View in Safari", @"launch safari to display the url"),
     NSLocalizedString(@"Settings", nil), nil];
     } else {// iOS >= 6.0
     NSString *social = [SLComposeViewController isAvailableForServiceType:SLServiceTypeSinaWeibo]
     ? @"Sina Weibo" : @"Facebook";
     self.actionSheet = [[UIActionSheet alloc] initWithTitle:nil
     delegate:self
     cancelButtonTitle:NSLocalizedString(@"Cancel", nil)
     destructiveButtonTitle:nil
     otherButtonTitles:
     NSLocalizedString(@"Bookmarks", @"Bookmarks"),
     social,
     NSLocalizedString(@"Tweet", @"Tweet the current url"),
     NSLocalizedString(@"Email URL", nil),
     NSLocalizedString(@"View in Safari", @"launch safari to display the url"),
     NSLocalizedString(@"Settings", nil), nil];
     }
     [self.actionSheet showInView:self];
     */
}


- (void)mailComposeController:(MFMailComposeViewController*)controller
          didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
    // Remove the mail view
    [self.browser dismissViewControllerAnimated:YES completion:NULL];
}

#pragma mark - UITextFieldDelegate
- (void)beginEdit{
    [self.searchField selectAll:self.searchField];
    [self presentSearchController];
    if(isInFullscreenMode){
        CGRect addressRect = self.frame;
        addressRect.origin.y = 0;
        self.frame = addressRect;
        self.browser.selectedViewController.view.alpha = 0;
    }
}
- (void)endEdit{
    if(self.isInFullscreenMode){
        self.browser.selectedViewController.view.alpha = 1;
        CGRect addressRect = self.frame;
        addressRect.origin.y = -self.frame.size.height;
        self.frame = addressRect;
        if(delegate && [delegate respondsToSelector:@selector(onPageToolbarEndEditWhenFullscreen)]){
            [delegate onPageToolbarEndEditWhenFullscreen];
        }
    }
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    [self beginEdit];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *searchText = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    // When the search string changes, filter the recents list accordingly.
    if (_searchMaskVisible && searchText.length) // TODO
        [self.searchController filterResultsUsingString:searchText];
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    // When the search button is tapped, add the search term to recents and conduct the search.
    NSString *searchString = [textField text];
    //    StringModifier* modifier = [[StringModifier alloc]init];
    //    NSString* _urlString=[modifier correctURL:searchString];
    
    [self finishSearch:searchString title:nil];
    [self endEdit];
    return YES;
}

#pragma mark - SGSearchController

- (void)presentSearchController {
    if (!_searchMaskVisible) {
        _searchMaskVisible = YES;
        self.searchController.view.frame = CGRectMake(0, self.frame.size.height,
                                                      self.frame.size.width, self.superview.bounds.size.height - self.frame.size.height);
        [UIView animateWithDuration:0.25
                         animations:^{
                             [self layoutSubviews];
                             _cancelButton.alpha = 1.0;
                             //_optionsButton.alpha = 0;
                             //_tabsButton.alpha = 0;
                             [self.superview addSubview:self.searchController.view];
                         } completion:^(BOOL finished){
                             //_optionsButton.hidden = YES;
                             //_tabsButton.hidden = YES;
                             _cancelButton.hidden = NO;
                         }];
    }
}

- (void)dismissSearchController {
    if (_searchMaskVisible) {
        _searchMaskVisible = NO;
        // If the user finishes editing text in the search bar by, for example:
        // tapping away rather than selecting from the recents list, then just dismiss the popover
        self.searchField.text = [self.browser URL].absoluteString;
        [UIView animateWithDuration:0.25
                         animations:^{
                             [self layoutSubviews];
                             //_optionsButton.alpha = 1.0;
                             //_tabsButton.alpha = 1.0;
                             _cancelButton.alpha = 0;
                             [self.searchController.view removeFromSuperview];
                         } completion:^(BOOL finished){
                             //_optionsButton.hidden = NO;
                             //_tabsButton.hidden = NO;
                             _cancelButton.hidden = YES;
                         }];
    }
}

- (void)userScrolledSuggestions {
    if ([self.searchField isFirstResponder])
        [self.searchField resignFirstResponder];
}

#pragma mark - SGSearchControllerDelegate

- (NSString *)text {
    return self.searchField.text;
}

- (void)finishSearch:(NSString *)searchString title:(NSString *)title {
    if (searchString.length > 0)// Conduct the search. In this case, simply report the search term used.
        [self.browser handleURLString:searchString title:title];
    
    [self dismissSearchController];
    [self.searchField resignFirstResponder];
    [self endEdit];
}

- (void)finishPageSearch:(NSString *)searchString {
    [self dismissSearchController];
    [self.searchField resignFirstResponder];
    [self.browser findInPage:searchString];
    [self endEdit];
}

@end
